<template>
  <div>
    <n-space vertical size="large">
      <!-- 活动管理部分 -->
      <n-card title="活动管理">
        <template #header-extra>
          <n-button type="primary" @click="router.push('/activity/create')">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
            创建活动
          </n-button>
        </template>

        <n-data-table
          :columns="activityColumns"
          :data="activities"
          :pagination="activityPagination"
          :loading="activityLoading"
        />
      </n-card>

      <!-- 需求管理部分 -->
      <n-card title="需求管理">
        <template #header-extra>
          <n-button type="primary" @click="router.push('/demand/publish')">
            <template #icon>
              <n-icon><AddOutline /></n-icon>
            </template>
            发布需求
          </n-button>
        </template>

        <n-data-table
          :columns="demandColumns"
          :data="demands"
          :pagination="demandPagination"
          :loading="demandLoading"
        />
      </n-card>
    </n-space>

    <!-- 活动报名管理弹窗 -->
    <n-modal v-model:show="enrollmentModalVisible" style="width: 900px">
      <n-card title="报名管理" :bordered="false">
        <template #header-extra>
          <n-space>
            <n-tag type="info">总报名：{{ enrollments.length }}</n-tag>
            <n-tag type="warning">待审核：{{ pendingCount }}</n-tag>
          </n-space>
        </template>

        <n-data-table 
          :columns="enrollmentColumns" 
          :data="enrollments"
          :pagination="{ pageSize: 10 }"
        />
      </n-card>
    </n-modal>

    <!-- 需求申请管理弹窗 -->
    <n-modal v-model:show="applicationModalVisible" style="width: 900px">
      <n-card title="申请管理" :bordered="false">
        <template #header-extra>
          <n-space>
            <n-tag type="info">总申请：{{ applications.length }}</n-tag>
            <n-tag type="warning">待审核：{{ pendingApplicationCount }}</n-tag>
          </n-space>
        </template>

        <n-data-table 
          :columns="applicationColumns" 
          :data="applications"
          :pagination="{ pageSize: 10 }"
        />
      </n-card>
    </n-modal>
  </div>
</template>

<script setup>
import { ref, reactive, h, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { NButton, NSpace, NTag, NPopconfirm, NAvatar } from 'naive-ui'
import { 
  getActivityList, 
  deleteActivity, 
  completeActivity, 
  getActivityEnrollments, 
  approveEnrollment,
  updateActivity
} from '@/api/activity'
import {
  getDemandList,
  deleteDemand,
  completeDemand,
  getDemandApplications,
  assignDemand,
  updateDemand
} from '@/api/demand'
import { getUserDetail } from '@/api/user'
import { AddOutline } from '@vicons/ionicons5'

const router = useRouter()

const activityLoading = ref(false)
const demandLoading = ref(false)
const activities = ref([])
const demands = ref([])
const enrollments = ref([])
const applications = ref([])
const enrollmentModalVisible = ref(false)
const applicationModalVisible = ref(false)
const currentActivityId = ref(null)
const currentDemandId = ref(null)

const pendingCount = computed(() => 
  enrollments.value.filter(e => e.status === 'ENROLLED').length
)

const pendingApplicationCount = computed(() =>
  applications.value.filter(a => a.status === 'APPLIED').length
)

const activityPagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page) => {
    activityPagination.page = page
    loadActivities()
  },
  onUpdatePageSize: (pageSize) => {
    activityPagination.pageSize = pageSize
    activityPagination.page = 1
    loadActivities()
  }
})

const demandPagination = reactive({
  page: 1,
  pageSize: 10,
  showSizePicker: true,
  pageSizes: [10, 20, 30],
  onChange: (page) => {
    demandPagination.page = page
    loadDemands()
  },
  onUpdatePageSize: (pageSize) => {
    demandPagination.pageSize = pageSize
    demandPagination.page = 1
    loadDemands()
  }
})

const activityColumns = [
  { title: '标题', key: 'title', width: 200, ellipsis: { tooltip: true } },
  { 
    title: '状态', 
    key: 'status',
    width: 100,
    render: (row) => {
      const typeMap = {
        DRAFT: 'warning',
        RECRUITING: 'success',
        IN_PROGRESS: 'info',
        COMPLETED: 'default'
      }
      const textMap = {
        DRAFT: '草稿',
        RECRUITING: '报名中',
        IN_PROGRESS: '进行中',
        COMPLETED: '已完成'
      }
      return h(NTag, { type: typeMap[row.status], size: 'small' }, { default: () => textMap[row.status] })
    }
  },
  { title: '地点', key: 'location', width: 150, ellipsis: { tooltip: true } },
  { 
    title: '报名人数', 
    key: 'currentParticipants',
    width: 100,
    render: (row) => `${row.currentParticipants}/${row.maxParticipants || '不限'}`
  },
  { title: '积分', key: 'pointsReward', width: 80 },
  {
    title: '操作',
    key: 'actions',
    width: 280,
    render: (row) => {
      return h(NSpace, { size: 'small' }, {
        default: () => [
          h(NButton, {
            size: 'small',
            onClick: () => router.push(`/activity/detail/${row.id}`)
          }, { default: () => '查看' }),
          h(NButton, {
            size: 'small',
            type: 'info',
            onClick: () => handleManageEnrollments(row.id)
          }, { default: () => '报名管理' }),
          row.status === 'RECRUITING' && h(NButton, {
            size: 'small',
            type: 'warning',
            onClick: () => handleChangeStatus(row.id, 'IN_PROGRESS')
          }, { default: () => '开始活动' }),
          row.status === 'IN_PROGRESS' && h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleComplete(row.id)
          }, { default: () => '完成活动' }),
          h(NPopconfirm, {
            onPositiveClick: () => handleDeleteActivity(row.id)
          }, {
            default: () => '确定删除此活动吗？',
            trigger: () => h(NButton, {
              size: 'small',
              type: 'error'
            }, { default: () => '删除' })
          })
        ]
      })
    }
  }
]

const demandColumns = [
  { title: '标题', key: 'title', width: 200, ellipsis: { tooltip: true } },
  { 
    title: '状态', 
    key: 'status',
    width: 100,
    render: (row) => {
      const typeMap = {
        PENDING: 'warning',
        ASSIGNED: 'info',
        IN_PROGRESS: 'primary',
        COMPLETED: 'success'
      }
      const textMap = {
        PENDING: '待接单',
        ASSIGNED: '已分配',
        IN_PROGRESS: '服务中',
        COMPLETED: '已完成'
      }
      return h(NTag, { type: typeMap[row.status], size: 'small' }, { default: () => textMap[row.status] })
    }
  },
  { title: '需求方', key: 'demanderName', width: 120 },
  { title: '地址', key: 'address', width: 150, ellipsis: { tooltip: true } },
  { title: '积分', key: 'pointsReward', width: 80 },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    render: (row) => {
      return h(NSpace, { size: 'small' }, {
        default: () => [
          h(NButton, {
            size: 'small',
            onClick: () => router.push(`/demand/detail/${row.id}`)
          }, { default: () => '查看' }),
          (row.status === 'PENDING' || row.status === 'ASSIGNED') && h(NButton, {
            size: 'small',
            type: 'info',
            onClick: () => handleManageApplications(row.id)
          }, { default: () => '申请管理' }),
          row.status === 'ASSIGNED' && h(NButton, {
            size: 'small',
            type: 'warning',
            onClick: () => handleStartDemand(row.id)
          }, { default: () => '开始服务' }),
          row.status === 'IN_PROGRESS' && h(NButton, {
            size: 'small',
            type: 'success',
            onClick: () => handleCompleteDemand(row.id)
          }, { default: () => '完成需求' }),
          h(NPopconfirm, {
            onPositiveClick: () => handleDeleteDemand(row.id)
          }, {
            default: () => '确定删除此需求吗？',
            trigger: () => h(NButton, {
              size: 'small',
              type: 'error'
            }, { default: () => '删除' })
          })
        ]
      })
    }
  }
]

const enrollmentColumns = [
  { 
    title: '用户ID', 
    key: 'userId',
    width: 100,
    render: (row) => {
      return h(NAvatar, { 
        size: 'small',
        style: { backgroundColor: '#18A058' }
      }, { default: () => row.userId })
    }
  },
  { 
    title: '状态', 
    key: 'status',
    width: 100,
    render: (row) => {
      const typeMap = {
        ENROLLED: 'info',
        APPROVED: 'success',
        REJECTED: 'error',
        COMPLETED: 'default'
      }
      const textMap = {
        ENROLLED: '待审核',
        APPROVED: '已通过',
        REJECTED: '已拒绝',
        COMPLETED: '已完成'
      }
      return h(NTag, { type: typeMap[row.status], size: 'small' }, { default: () => textMap[row.status] })
    }
  },
  { title: '报名理由', key: 'applyReason', ellipsis: { tooltip: true } },
  { 
    title: '报名时间', 
    key: 'createTime',
    width: 180,
    render: (row) => new Date(row.createTime).toLocaleString('zh-CN')
  },
  {
    title: '操作',
    key: 'actions',
    width: 160,
    render: (row) => {
      if (row.status === 'ENROLLED') {
        return h(NSpace, { size: 'small' }, {
          default: () => [
            h(NButton, {
              size: 'small',
              type: 'success',
              onClick: () => handleApprove(row.id, 'APPROVED', row.userId)
            }, { default: () => '通过' }),
            h(NButton, {
              size: 'small',
              type: 'error',
              onClick: () => handleApprove(row.id, 'REJECTED', row.userId)
            }, { default: () => '拒绝' })
          ]
        })
      }
      return h('span', { style: { color: '#999' } }, '已处理')
    }
  }
]

const applicationColumns = [
  { 
    title: '用户ID', 
    key: 'userId',
    width: 100,
    render: (row) => {
      return h(NAvatar, { 
        size: 'small',
        style: { backgroundColor: '#18A058' }
      }, { default: () => row.userId })
    }
  },
  { 
    title: '状态', 
    key: 'status',
    width: 100,
    render: (row) => {
      const typeMap = {
        APPLIED: 'info',
        APPROVED: 'success',
        REJECTED: 'error'
      }
      const textMap = {
        APPLIED: '待审核',
        APPROVED: '已通过',
        REJECTED: '已拒绝'
      }
      return h(NTag, { type: typeMap[row.status], size: 'small' }, { default: () => textMap[row.status] })
    }
  },
  { title: '申请理由', key: 'reason', ellipsis: { tooltip: true } },
  { 
    title: '申请时间', 
    key: 'createTime',
    width: 180,
    render: (row) => new Date(row.createTime).toLocaleString('zh-CN')
  },
  {
    title: '操作',
    key: 'actions',
    width: 160,
    render: (row) => {
      if (row.status === 'APPLIED') {
        return h(NSpace, { size: 'small' }, {
          default: () => [
            h(NButton, {
              size: 'small',
              type: 'success',
              onClick: () => handleApproveApplication(row.demandId, row.userId)
            }, { default: () => '通过并分配' }),
            h(NButton, {
              size: 'small',
              type: 'error',
              onClick: () => handleRejectApplication(row.id)
            }, { default: () => '拒绝' })
          ]
        })
      }
      return h('span', { style: { color: '#999' } }, '已处理')
    }
  }
]

const loadActivities = async () => {
  activityLoading.value = true
  try {
    const res = await getActivityList({
      page: activityPagination.page,
      size: activityPagination.pageSize
    })
    activities.value = res.data.records || []
    activityPagination.itemCount = res.data.total || 0
  } catch (error) {
    console.error('加载活动失败:', error)
  } finally {
    activityLoading.value = false
  }
}

const loadDemands = async () => {
  demandLoading.value = true
  try {
    const res = await getDemandList({
      page: demandPagination.page,
      size: demandPagination.pageSize
    })
    demands.value = res.data.records || []
    demandPagination.itemCount = res.data.total || 0
  } catch (error) {
    console.error('加载需求失败:', error)
  } finally {
    demandLoading.value = false
  }
}

const handleManageEnrollments = async (activityId) => {
  currentActivityId.value = activityId
  try {
    const res = await getActivityEnrollments(activityId)
    enrollments.value = res.data || []
    enrollmentModalVisible.value = true
  } catch (error) {
    console.error('加载报名列表失败:', error)
    window.$message?.error('加载报名列表失败')
  }
}

const handleManageApplications = async (demandId) => {
  currentDemandId.value = demandId
  try {
    const res = await getDemandApplications(demandId)
    applications.value = res.data || []
    applicationModalVisible.value = true
  } catch (error) {
    console.error('加载申请列表失败:', error)
    window.$message?.error('加载申请列表失败')
  }
}

const handleApprove = async (enrollmentId, status, userId) => {
  try {
    await approveEnrollment(enrollmentId, { status })
    
    const statusText = status === 'APPROVED' ? '已通过' : '已拒绝'
    window.$message?.success(`审核${statusText}`)
    
    // 刷新报名列表
    handleManageEnrollments(currentActivityId.value)
    
    // TODO: 可以在这里添加系统通知，通知用户审核结果
    // 简化版：在用户下次查看"我的活动"时会看到状态更新
  } catch (error) {
    console.error('审核失败:', error)
  }
}

const handleApproveApplication = async (demandId, userId) => {
  try {
    await assignDemand(demandId, { userId })
    window.$message?.success('已分配给该志愿者')
    
    // 刷新申请列表和需求列表
    handleManageApplications(demandId)
    loadDemands()
  } catch (error) {
    console.error('分配失败:', error)
  }
}

const handleRejectApplication = async (applicationId) => {
  // 这里可以添加拒绝申请的API，目前简化处理
  window.$message?.info('拒绝功能待实现')
}

const handleChangeStatus = async (activityId, newStatus) => {
  try {
    const activity = activities.value.find(a => a.id === activityId)
    await updateActivity(activityId, { ...activity, status: newStatus })
    window.$message?.success('状态更新成功')
    loadActivities()
  } catch (error) {
    console.error('状态更新失败:', error)
  }
}

const handleComplete = async (activityId) => {
  try {
    await completeActivity(activityId)
    window.$message?.success('活动已完成，积分已发放')
    loadActivities()
  } catch (error) {
    console.error('完成活动失败:', error)
  }
}

const handleStartDemand = async (demandId) => {
  try {
    const demand = demands.value.find(d => d.id === demandId)
    if (!demand) return
    
    await updateDemand(demandId, { 
      ...demand, 
      status: 'IN_PROGRESS' 
    })
    window.$message?.success('服务已开始')
    loadDemands()
  } catch (error) {
    console.error('更新状态失败:', error)
    window.$message?.error('操作失败')
  }
}

const handleCompleteDemand = async (demandId) => {
  try {
    // 调用完成需求API，后端会自动发放积分
    await completeDemand(demandId)
    window.$message?.success('需求已完成，积分已发放')
    loadDemands()
  } catch (error) {
    console.error('完成需求失败:', error)
    window.$message?.error('操作失败')
  }
}

const handleDeleteActivity = async (activityId) => {
  try {
    await deleteActivity(activityId)
    window.$message?.success('删除成功')
    loadActivities()
  } catch (error) {
    console.error('删除活动失败:', error)
  }
}

const handleDeleteDemand = async (demandId) => {
  try {
    await deleteDemand(demandId)
    window.$message?.success('删除成功')
    loadDemands()
  } catch (error) {
    console.error('删除需求失败:', error)
  }
}

onMounted(() => {
  loadActivities()
  loadDemands()
})
</script>
